const db = uniCloud.databaseForJQL()
const _ = db.command

import {
	getGridCode,
	getSurroundingGrids
} from './getSurroundingGrids'


/**
 * 获取公共消息
 */
export async function getPublicMsg(user,location, skip,lastTime) {
   
	        if (!user || typeof user !== 'object' || !user.userId) { // 假设 userId 是用户唯一标识
	          console.warn(' 用户信息无效（缺少 user 或 userId）', user);
	          return; // 无有效用户，不执行后续操作
	        }
	
	   
	        if (!location || typeof location !== 'object' || 
	            location.longitude === undefined || location.latitude === undefined) {
	          console.warn(' 新位置信息无效（缺少 longitude 或 latitude）', location);
	          return; // 位置无效，终止执行
	        }
	

	try {
		const centerGrid = getGridCode(location)
		const aroundGrids = getSurroundingGrids(centerGrid, 5)
		const lastTime72 =lastTime?lastTime: new Date().getTime() - 72 * 3600 * 1000;

		const res = await db.collection('message_public')
			.where({
				grid: _.in(aroundGrids),
				timestamp: _.gt(lastTime72)
			})
			.orderBy('timestamp', 'desc')
			.limit(100)
			.skip(skip||0)
			.get();
	
		const messages = res.data
		const processMsg = messages.map(item => {
			const isSended = true
			return {
				...item,
				isSended
			}
		})
		return {
			success: true,
			data: processMsg

		};
	} catch (e) {
		console.error("获取公共消息失败:", e.message);
		return {
			success: false,
			error: e.message
		};
	}
}

/**
 * 获取群消息
 */
export async function getGroupMsg(user) {

	try {
		// 获取用户加入的群组
		const getGroup = await db.collection('linli-user').where({
			userId: user.userId
		}).field({
			addedGroup: true
		}).get()

		if (getGroup.data[0]?.addedGroup?.length > 0) {
			const addedGroup = getGroup.data[0].addedGroup
			for (const groupId of addedGroup) {
				const lastTime = await getLastTime(groupId)
				const res = await db.collection('message_group')
					.where({
						'toTarget.targetId': groupId,
						'timestamp': _.gt(lastTime)
					})
					.limit(1000)
					.get();

				await SaveGroupMsg(res, groupId, lastTime);
				uni.$emit("newMsgNotice", res.data)
			}
		}
	} catch (e) {
		console.error("获取群消息失败:", e.message);
		return {
			success: false,
			error: e.message
		};
	}
}

/**
 * 获取个人消息
 */
export async function getPersonMsg(user) {

	const lastTime = await getLastTime('person')


	try {
		const res = await db.collection('message_person')
			.where(_.or([{
					// 条件1：用户发送的消息
					'sendUserId': user.userId,
					"timestamp": _.gt(lastTime)
				},
				{
					// 条件2：发送给用户的消息
					'toTarget.targetId': user.userId,
					"timestamp": _.gt(lastTime)
				}
			]))
			.limit(1000)
			.get();

		if (res.data.length > 0) {
			let maxTime = lastTime
			for (const msg of res.data) {
				if (msg.timestamp > maxTime) {
					maxTime = msg.timestamp
				}
				const targetId = msg.sendUserId === user.userId ? msg.toTarget.targetId : msg.sendUserId
				await saveChatRecords(targetId, [msg])
			}
			console.log('个人新消息通知', res.data);
			uni.$emit("newMsgNotice", res.data)
			await uni.setStorage({
				key: "msgLastTime_person",
				data: maxTime
			})
		}
	} catch (e) {
		console.error("获取个人消息失败:", e.message);
		return {
			success: false,
			error: e.message
		};
	}
}

/**
 * 处理并保存群消息
 */
async function SaveGroupMsg(res, id, lastTime) {
	if (!res || !res.data || res.data.length === 0) {
		return {
			success: true,
			data: []
		};
	}

	// 按发送者/群组ID分组消息
	let maxTimestamp = lastTime;
	res.data.forEach((item) => {
		if (item.timestamp > maxTimestamp) {
			maxTimestamp = item.timestamp;
		}
	})

	await uni.setStorage({
		key: `msgLastTime_${id}`,
		data: maxTimestamp
	})

	await saveChatRecords(id, res.data);
}

/**
 * 保存聊天记录到本地存储
 */
async function saveChatRecords(id, messages) {
	try {
		const storageKey = `msg_${id}`
		let existingData = []

		try {
			const result = await uni.getStorage({
				key: storageKey
			})
			existingData = result.data || []
		} catch (err) {
			// 存储不存在时，使用空数组
		}

		const mergedMessages = [...existingData, ...messages]
			.sort((a, b) => a.timestamp - b.timestamp);

		await uni.setStorage({
			key: storageKey,
			data: mergedMessages
		})

		console.log(`成功保存 ${storageKey} 的 ${messages.length} 条消息`);
	} catch (err) {
		console.error('保存消息记录时出错:', err);
	}
}

/**
 * 获取上次消息时间戳
 */
async function getLastTime(id) {
	try {
		const key = `msgLastTime_${id}`
		const result = await uni.getStorage({
			key
		})

		if (result.data) {
			return result.data
		} else {
			const dataNow = new Date().getTime() // 修正构造函数名称
			await uni.setStorage({
				key,
				data: dataNow
			})
			return dataNow
		}
	} catch (e) {
		console.error("最后时间获取错误", e)
		// 返回一个较早的时间戳作为默认值
		return new Date().getTime() - 30 * 24 * 3600 * 1000 // 默认30天前
	}
}